//通过vue-router插件实现模板路由配置
import { createRouter, createWebHashHistory } from 'vue-router'
import { constantRoute } from './routes'
import nprogress from 'nprogress'
//引入进度条样式
import 'nprogress/nprogress.css'
import pinia from '@/store'
import useUserStore from '@/store/modules/user'

nprogress.configure({ showSpinner: false })
const userStore = useUserStore(pinia)
//创建路由器
const router = createRouter({
  //路由模式hash
  history: createWebHashHistory(),
  routes: constantRoute,
  //滚动行为
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    }
  },
})
//to:你将要访问那个路由
//from:你从来个路由而来
//next:路由的放行函数
router.beforeEach(async (to: any, from: any, next: any) => {
  if (!from) {
    return
  }
  document.title = to.meta ? `${to.meta.title}` : ''
  nprogress.start()
  //获取 accessToken
  const accessToken = userStore.userState.accessToken
  const userInfo = userStore.userState.userInfo
  if (accessToken) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (userInfo) {
        next()
      } else {
        await userStore.getUserInfo()
        next({ ...to })
        // next({ path: '/login', query: { redirect: to.path } })
      }
    }
  } else {
    //用户未登录判断
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

// eslint-disable-next-line @typescript-eslint/no-unused-vars
router.afterEach(() => {
  nprogress.done()
})

export default router
